package com.buptlogistics.creditinvestigation.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SignUpCallback;
import com.buptlogistics.creditinvestigation.R;
import com.buptlogistics.creditinvestigation.activity.MainActivity;
import com.buptlogistics.creditinvestigation.app.AppData;
import com.buptlogistics.creditinvestigation.app.BaseFragment;
import com.buptlogistics.creditinvestigation.entity.User;
import com.buptlogistics.creditinvestigation.utils.ToastUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegistFragment extends BaseFragment {
    private View view;
    private EditText tv_username, tv_password, tv_phone, tv_company, tv_company_code;
    private Button btn_registe;
    private boolean isenable;


    // 进度条
    public static ProgressDialog progressDialog = null;

    public RegistFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        view = inflater.inflate(R.layout.fragment_regist, container, false);
        // LeanCloudUtil.getInstance(getActivity());
        // LeanCloud
        // 如果使用美国节点，请加上这行代码 AVOSCloud.useAVCloudUS();


        AppData.getInstance(RegistFragment.this.getActivity());

        initViews();
        initEvents();
        return view;
    }

    protected void initViews() {
        isenable = true;
        // TODO Auto-generated method stub
        tv_username = (EditText) view.findViewById(R.id.met_regist_name_register);
        // emils = (EditText) view.findViewById(R.id.emils_register);
        tv_password = (EditText) view.findViewById(R.id.met_regist_password_register);
        tv_phone = (EditText) view.findViewById(R.id.met_regist_phone_num);
        tv_company = (EditText) view.findViewById(R.id.met_regist_company);
        tv_company_code = (EditText) view.findViewById(R.id.met_regist_company_code);

        btn_registe = (Button) view.findViewById(R.id.btn_registe);

    }

    protected void initEvents() {
        // TODO Auto-generated method stub
        btn_registe.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final String user_name = tv_username.getText().toString();
                // String user_emils = emils.getText().toString();
                // String user_emils = "12345678@163.com";
                final String user_password = tv_password.getText().toString();
                final String user_phone = tv_phone.getText().toString();
                final String user_company = tv_company.getText().toString();
                final String user_company_code = tv_company_code.getText().toString();

                /**
                 * 检查是否有空值
                 * */
                if (TextUtils.isEmpty(tv_username.getText())) {
                    ToastUtil.showToast(RegistFragment.this.getActivity(),
                            "用户名不能为空");
                    return;
                    // }
                    // else if (TextUtils.isEmpty(emils.getText())) {
                    // Toast.makeText(RegistFragment.this.getActivity(),
                    // "邮箱不能为空",
                    // Toast.LENGTH_SHORT).show();
                    // return;
                } else if (TextUtils.isEmpty(tv_password.getText())) {
                    ToastUtil.showToast(RegistFragment.this.getActivity(),
                            "密码不能为空");
                    return;
                } else if (TextUtils.isEmpty(tv_phone.getText())) {
                    ToastUtil.showToast(RegistFragment.this.getActivity(),
                            "手机号不能为空");
                    return;
                } else if (TextUtils.isEmpty(tv_company.getText())) {
                    ToastUtil.showToast(RegistFragment.this.getActivity(),
                            "公司名不能为空");
                    return;
                } else if (TextUtils.isEmpty(tv_company_code.getText())) {
                    ToastUtil.showToast(RegistFragment.this.getActivity(),
                            "组织机构代码不能为空");
                    return;
                }

                /**
                 * 检查昵称格式，中英文字母下划线数字
                 * */
                String checkName = "^[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}+$";







                Pattern regexName = Pattern.compile(checkName);
                Matcher matcherName = regexName.matcher(user_name);
                if (!(matcherName.matches())) {
                    Toast.makeText(RegistFragment.this.getActivity(),
                            "用户名格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                /**
                 * 检查密码格式
                 * */
                String checkPassword = "^[a-zA-Z0-9_]{6,16}$";
                Pattern regexPassword = Pattern.compile(checkPassword);
                Matcher matcherPassword = regexPassword.matcher(user_password);
                if (!(matcherPassword.matches())) {
                    Toast.makeText(RegistFragment.this.getActivity(),
                            "密码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                /**
                 * 检查手机号格式
                 * */
                String checkPhone = "^[0-9]{11}$";
                Pattern regexPhone = Pattern.compile(checkPhone);
                Matcher matcherPhone = regexPhone.matcher(user_phone);
                if (!(matcherPhone.matches())) {
                    Toast.makeText(RegistFragment.this.getActivity(),
                            "手机号格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                /**
                 * 检查公司格式
                 * */
                String checkCompany = "^[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}+$";
                Pattern regexCompany = Pattern.compile(checkCompany);
                Matcher matcherCompany = regexCompany.matcher(user_company);
                if (!(matcherCompany.matches())) {
                    Toast.makeText(RegistFragment.this.getActivity(),
                            "公司格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                /**
                 * 检查公司代号格式
                 * */
                String checkCompanyCode = "^[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}+$";
                Pattern regexCompanyCode = Pattern.compile(checkCompanyCode);
                Matcher matcherCompanyCode = regexCompanyCode.matcher(user_company_code);
                if (!(matcherCompanyCode.matches())) {
                    Toast.makeText(RegistFragment.this.getActivity(),
                            "公司代号格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                /*
     * <p>
     * Title: regist
     * </p>
     * <p>
     * Description:注册
     * </p>
     *
     * @param userName
     * @param password
     * @param user
     */
                final Context nContext = getActivity();
                AppData.getInstance(nContext);
                final AVUser avuser = new AVUser();
                avuser.setUsername(user_name);
                avuser.setPassword(user_password);
                // 其他属性可以像其他AVObject对象一样使用put方法添加

                avuser.put("phone", user_phone);
                avuser.put("company",user_company);
                avuser.put("company_code", user_company_code);
                avuser.signUpInBackground(new SignUpCallback() {
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            Log.i("success", "regist success");
                            Toast.makeText(nContext, "注册成功", Toast.LENGTH_SHORT).show();
                            User user=new User(user_name,user_password,user_phone,user_company,user_company_code);
                            AppData.getInstance(nContext).saveUserInfo(user.toString());
                            Log.i("user",user.toString());
//                    AppData.getInstance(nContext).setUserPassword(password);
                            AppData.getInstance(nContext).setLogin(true);
                            Intent intent = new Intent(nContext, MainActivity.class);
                            // 启动intent对应的Activity
                            ((Activity) nContext).startActivity(intent);
                            ((Activity) nContext).finish();
                        } else {
                            Log.e("failed", e.toString());
                            Toast.makeText(nContext, "用户名已被占用", Toast.LENGTH_SHORT)
                                    .show();
                            ((Activity) nContext).finish();
                        }
                    }
                });
            }


            // /////////////////////////////
           /*   progressDialog = ProgressDialog.show(
                        RegistFragment.this.getActivity(), "请稍等", "数据处理中...",
                        true);*/
            // ///////////*///////////////////

            String gender = "";
            //User user = new User(user_name, gender);
            //TODO
            //IcyBeeUtil.regist(user_name,
            //        user_password, user_phone, user_company, user_company_code, getActivity());

        });
    }


    //try {
    //    Jsoup.connect(registUrl).data(param).get();
    //} catch (IOException e) {
    //    e.printStackTrace();
    //}

    //private void login(String userName, String password) {
    //    RequestParams requestParams = new RequestParams();
    //    requestParams.add("user_name", userName);
    //    requestParams.add("user_pass", password);
    //    HttpUtil.get(Constants.getLoginUrl(), requestParams, new AsyncHttpResponseHandler() {
    //        @Override
    //        public void onSuccess(int i, Header[] headers, byte[] bytes) {
    //            ToastUtil.showToast(RegistFragment.this.getActivity(), "注册登录成功");
    //            JSONObject jsonObject = JSONObject.parseObject(new String(bytes));
    //            AppData.getInstance(RegistFragment.this.getActivity()).saveTooken(jsonObject.getString("token"));
    //            AppData.getInstance(RegistFragment.this.getActivity()).setLogin(true);
    //            Logcat.i("bytes", jsonObject.toJSONString());
    //            RegistFragment.this.getActivity().finish();
    //        }
    //
    //        @Override
    //        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
    //            AppData.getInstance(RegistFragment.this.getActivity()).setLogin(false);
    //            Logcat.i("bytes", new String(bytes));
    //        }
    //    });
    //}

    // /**
    // * <p>
    // * Title: regist
    // * </p>
    // * <p>
    // * Description:注册
    // * </p>
    // *
    // * @param userName
    // * @param password
    // * @param tableUser
    // *
    // */
    // private void regist(String userName, final String password,
    // TableUser tableUser) {
    // AVUser avuser = new AVUser();
    // avuser.setUsername(userName);
    // avuser.setPassword(password);
    // // 其他属性可以像其他AVObject对象一样使用put方法添加
    // avuser.put("tableUser", tableUser);
    // if (tableUser.isByr()) {
    // avuser.put("showName", tableUser.getUserName());
    // } else {
    // avuser.put("showName", userName);
    // }
    // avuser.signUpInBackground(new SignUpCallback() {
    // @Override
    // public void done(AVException e) {
    // if (e == null) {
    // Log.i("success", "regist success");
    // Toast.makeText(RegistFragment.this.getActivity(), "注册成功",
    // Toast.LENGTH_SHORT).show();
    // AppData.getInstance(getActivity())
    // .setUserPassword(password);
    // ((Activity) RegistFragment.this.getActivity()).finish();
    // } else {
    // Log.e("failed", e.toString());
    // Toast.makeText(RegistFragment.this.getActivity(),
    // "用户名已被占用", Toast.LENGTH_SHORT).show();
    // }
    // }
    // });
    // }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }
}


